package com.party.system.utils;

import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.time.LocalDateTime;

/**
 * @FileName: wuliu
 * @author: 王晨旭
 * @date: 2025/3/11 10:10
 * @Description:
 */
public class CustomMultipartFile implements MultipartFile {

    private final byte[] fileContent;
    private final String fileName;
    private final String contentType;
    private final LocalDateTime expireTime; // 过期时间

    /**
     * 适用于需要设置过期时间的文件
     */
    public CustomMultipartFile(byte[] fileContent, String fileName, String contentType, long expirationMinutes) {
        this.fileContent = fileContent;
        this.fileName = fileName;
        this.contentType = contentType;
        this.expireTime = LocalDateTime.now().plusMinutes(expirationMinutes); // 计算过期时间
    }

    /**
     * 适用于不过期的文件
     */
    public CustomMultipartFile(byte[] fileContent, String fileName, String contentType) {
        this.fileContent = fileContent;
        this.fileName = fileName;
        this.contentType = contentType;
        this.expireTime = null; // 永不过期
    }

    /**
     * 检查文件是否已过期
     */
    public boolean isExpired() {
        return expireTime != null && LocalDateTime.now().isAfter(expireTime);
    }

    @Override
    public String getName() {
        return fileName;
    }

    @Override
    public String getOriginalFilename() {
        return fileName;
    }

    @Override
    public String getContentType() {
        return contentType;
    }

    @Override
    public boolean isEmpty() {
        return fileContent.length == 0;
    }

    @Override
    public long getSize() {
        return fileContent.length;
    }

    @Override
    public byte[] getBytes() {
        return fileContent;
    }

    @Override
    public InputStream getInputStream() {
        return new ByteArrayInputStream(fileContent);
    }

    @Override
    public void transferTo(File dest) throws IOException {
        if (isExpired()) {
            throw new IOException("文件已过期，无法保存！");
        }
        try (FileOutputStream fos = new FileOutputStream(dest)) {
            fos.write(fileContent);
        }
    }
}
